/**
 * https://leetcode.cn/submissions/detail/558827690/
 * 1838. 最高频元素的频数
 * medium 黄伟杰 2024.8.27
 * 滑动窗口
 */

#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
    int maxFrequency(vector<int> &nums, int k)
    {
        sort(nums.begin(), nums.end());
        long long sum = 0;
        int i = 0, j = 1, ans = 0;
        for (; j < nums.size(); j++)
        {
            int pre = nums[j] - nums[j - 1];
            sum += (long long)(j - i) * pre;
            while (sum > k)
            {
                sum -= nums[j] - nums[i];
                i++;
            }
            ans = max(ans, (j - i + 1));
        }
        if (nums.size() == 1)
            return 1;
        return ans;
    }
};